﻿/*
 * Almathy Center - KeyboardHook.cs
 * Copyright (C) 2011 Christophe LEMOINE
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * */
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace AlmathyCenter.Datas
{

    public class KeyboardHook
    {

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardProcedure lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_SYSKEYDOWN = 0x0104;

        private IntPtr SetHook(KeyboardProcedure proc)
        {
            using (Process currentProcess = Process.GetCurrentProcess())
                using (ProcessModule currentModule = currentProcess.MainModule)
                    return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(currentModule.ModuleName), 0);
        }
 
        private delegate IntPtr KeyboardProcedure(int nCode, IntPtr wParam, IntPtr lParam);

        public delegate void KeyPressDetectedHandler(object sender, Key key);
        public event KeyPressDetectedHandler KeyPressDetected;
 
        private void OnKeyPressDetected(object sender, Key args)
        {
            if (KeyPressDetected != null)
                KeyPressDetected(sender, args);
        }
 
        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN))
            {
                int vkCode = Marshal.ReadInt32(lParam);
                Key key = ((Key)vkCode);
                OnKeyPressDetected(null, key);
            }
            return CallNextHookEx(keyboardHookId, nCode, wParam, lParam);
        }

        private KeyboardProcedure keyboardProcedure;
        private KeyboardProcedure CurrentKeyboardProcedure
        {
            get
            {
                if (keyboardProcedure == null)
                {
                    keyboardProcedure = HookCallback;
                }
                return keyboardProcedure;
            }
            set { keyboardProcedure = value; }
        }

        private IntPtr keyboardHookId = IntPtr.Zero;

        public KeyboardHook()
        {
            keyboardHookId = SetHook(CurrentKeyboardProcedure);
        }

        public void Dispose()
        {
            UnhookWindowsHookEx(keyboardHookId);
        }

    }

}
